package com.suneee.refund.job;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.poi.util.SystemOutLogger;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.StatefulJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.suneee.base.util.ContextHelper;
import com.suneee.base.util.JsonUtil;
import com.suneee.core.util.StringUtils;
import com.suneee.refund.dao.RefundApplyDao;
import com.suneee.refund.dao.RefundCommentDao;
import com.suneee.refund.entity.RefundApply;
import com.suneee.refund.entity.RefundComment;
import com.suneee.refund.params.RefundParams;
import com.suneee.refund.util.ReflectUtil;
import com.suneee.shop.dao.ShopDao;
import com.suneee.shop.entity.Shop;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.Refund;
import com.taobao.api.domain.RefundMessage;
import com.taobao.api.request.RefundGetRequest;
import com.taobao.api.request.RefundMessagesGetRequest;
import com.taobao.api.request.RefundsReceiveGetRequest;
import com.taobao.api.response.RefundGetResponse;
import com.taobao.api.response.RefundMessagesGetResponse;
import com.taobao.api.response.RefundsReceiveGetResponse;

public class RefundApplyDetailJob implements StatefulJob {

	private static final Logger logger = LoggerFactory.getLogger(RefundApplyDetailJob.class);
	
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		ShopDao shopDao =  ContextHelper.getBean("shopDao", ShopDao.class);
		RefundApplyDao refundApplyDao = ContextHelper.getBean("refundApplyDao", RefundApplyDao.class);
		RefundCommentDao refundCommentDao = ContextHelper.getBean("refundCommentDao", RefundCommentDao.class);
		JobDataMap dataMap = context.getJobDetail().getJobDataMap();
		String jobName = context.getJobDetail().getName();
		String shopId = dataMap.getString("shopId");	
		if(StringUtils.isEmpty(shopId))
		{
			logger.error("-------------------------店铺ID 为空----------------------------------");
			return ;
		}
		Shop shop = shopDao.get(Integer.valueOf((shopId))); 
		String jsonStr = shop.getRuleInfo();
		String proxUrl = shop.getProxyURL();
		
		logger.info("调度任务--"+jobName+" 开始时间....."+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		
		Map<String,String> shopMap = JsonUtil.parse(jsonStr);
		shopMap.put("proxUrl", proxUrl);
		try {
			//调用淘宝售后列表信息接口
			RefundsReceiveGetResponse response = this.getRefundApply(shopMap);
			if(response.getTotalResults() == 0)
			{
				return;
			}
			List<Refund> list = response.getRefunds();
			List<RefundApply> applyList = new ArrayList<>();
			List<RefundApply> updApplyList = new ArrayList<>();
			List<RefundComment> commentList = new ArrayList<>();
			List<RefundComment> updateComList = new ArrayList<>();
			for(Refund refund : list){
				
				//调用淘宝售后详细信息接口
				RefundGetResponse detailRsp = this.getDetailRefundApply(shopMap, refund.getRefundId());
				if(detailRsp.getRefund() == null)
				{
					continue;
				}
				Refund temp = detailRsp.getRefund();
				RefundApply applyTemp = refundApplyDao.select(String.valueOf(temp.getRefundId()));
				
				//|| "CLOSED".equals(applyTemp.getStatus()) || "SELLER_REFUSE_BUYER".equals(applyTemp.getStatus())
				//对从淘宝拉取的售后订单。  进行逻辑处理->售后订单不存在(中台)  则保存最新的售后信息。
				if(applyTemp == null)
				{
					RefundApply apply = new RefundApply();
					ReflectUtil.tmallRefundValueChanger(temp, apply);
					apply.setFeedbackTime(null);
					applyList.add(apply);
				}
				else
				{
					//或中台售后单信息状态是INIT，DENY，PROCESS 则更新售后单信息。
					if("INIT".equals(applyTemp.getProcessStatus()) 
							|| "DENY".equals(applyTemp.getProcessStatus()) 
							|| "SELLER_REFUSE_BUYER".equals(applyTemp.getStatus())
							|| "PROCESS".equals(applyTemp.getProcessStatus()))
					{
						String status = applyTemp.getStatus();
						String process = applyTemp.getProcessStatus();
						//非PROCESS 状态下 就更新整个售后单信息。 
						if(!"PROCESS".equals(applyTemp.getProcessStatus()))
						{
							ReflectUtil.tmallRefundValueChanger(temp, applyTemp);
							if(!"CLOSED".equals(status) && !"DENY".equals(process))
							{
								applyTemp.setStatus(status);
								applyTemp.setProcessStatus(process);	
							}
							applyTemp.setFeedbackTime(null);
							updApplyList.add(applyTemp);
						}
						else
						{
							//判断拉取的售后单信息是否包含退货快递信息。
							if(!StringUtils.isEmpty(temp.getSid()) && !StringUtils.isEmpty(temp.getCompanyName()))
							{
								Timestamp timestamp = new Timestamp(System.currentTimeMillis());
								applyTemp.setSid(temp.getSid());
								applyTemp.setCompanyName(temp.getCompanyName());
								applyTemp.setUpdatedAt(timestamp);
								applyTemp.setStatus(status);
								applyTemp.setProcessStatus(process);
								applyTemp.setFeedbackTime(null);
								updApplyList.add(applyTemp);
							}
						}
					}
					/*
					 *if(StringUtils.isEmpty(applyTemp.getFeedbackStatus()) && "REFUND_GOODS".equals(applyTemp.getAfterSaleType())
							&& ("INIT".equals(applyTemp.getProcessStatus()) || "PROCESS".equals(applyTemp.getProcessStatus())))
					{
						//判断拉取的售后单信息是否包含退货快递信息。
						if(!StringUtils.isEmpty(temp.getSid()) && !StringUtils.isEmpty(temp.getCompanyName()))
						{
							Timestamp timestamp = new Timestamp(System.currentTimeMillis());
							applyTemp.setSid(temp.getSid());
							applyTemp.setCompanyName(temp.getCompanyName());
							applyTemp.setUpdatedAt(timestamp);
							updApplyList.add(applyTemp);
						}	
						
					} 
					 * String afertSale = null;
					if(temp.getHasGoodReturn())
					{
						afertSale = RefundParams.AFTER_SALE_TYPE_REFUND_REFUND_GOODS;
					}
					else
					{
						afertSale =  RefundParams.AFTER_SALE_TYPE_REFUND_MONEY;
					}
					 && !afertSale.equals(applyTemp.getAfterSaleType())
*/					
				}
				
				RefundMessagesGetResponse refundMsg = getRefundMessages(shopMap, temp.getRefundId(),temp.getRefundPhase());
				if(refundMsg.getRefundMessages() != null && !refundMsg.getRefundMessages().isEmpty()){
					for(RefundMessage msg : refundMsg.getRefundMessages())
					{
						RefundComment comment = new RefundComment();
						ReflectUtil.refundMessageValueChanger(msg, comment);
						RefundComment comnent = refundCommentDao.getCommentByRefundId(String.valueOf(msg.getRefundId()));
						
						//对从淘宝拉取的售后买家留言进行逻辑处理。   
						if(comnent == null)
						{
							commentList.add(comment);
						}
						else
						{
							//comnent.setContent(msg.getContent());
							//comnent.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
							ReflectUtil.refundMessageValueChanger(msg, comment);
							updateComList.add(comnent);
						}
					}
				}
			}
			if(applyList.size() > 0)
			{
				refundApplyDao.insert(applyList);
			}
			
			if(updApplyList.size() > 0)
			{
				refundApplyDao.update(updApplyList);
			}
			
			if(commentList.size() > 0)
			{
				refundCommentDao.insert(commentList);
			}
			if(updateComList.size() > 0)
			{
				refundCommentDao.update(updateComList);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		logger.info("调度任务--"+jobName+" 结束时间....."+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
	}

	private RefundsReceiveGetResponse getRefundApply(Map<String,String> params) throws Exception{
		TaobaoClient client = new DefaultTaobaoClient(params.get("proxUrl"), params.get("appKey"), params.get("secret"));
		RefundsReceiveGetRequest req = new RefundsReceiveGetRequest();
		req.setFields("refund_id, tid, title, buyer_nick, seller_nick, total_fee, status, created, refund_fee, oid, good_status, company_name, sid, payment, reason, desc, has_good_return, modified, order_status,refund_phase");
		req.setStatus("WAIT_SELLER_AGREE");
		RefundsReceiveGetResponse response = client.execute(req , params.get("appSession"));
		return response;
	}

	private RefundGetResponse getDetailRefundApply(Map<String,String> params,Long refundId) throws Exception{
		TaobaoClient client = new DefaultTaobaoClient(params.get("proxUrl"), params.get("appKey"), params.get("secret"));
		RefundGetRequest req = new RefundGetRequest();
		req.setFields("refund_id, alipay_no, tid, oid, buyer_nick, seller_nick, total_fee, "
				+ "status, created, refund_fee, good_status, has_good_return, payment, "
				+ "reason, desc, num_iid, title, price, num, good_return_time, company_name, "
				+ "sid, address, shipping_type, refund_remind_timeout, refund_phase, "
				+ "refund_version, operation_contraint, attribute, outer_id, sku");
		req.setRefundId(refundId);
		RefundGetResponse rsp = client.execute(req, params.get("appSession"));
		return rsp;
	}
	
	public static RefundMessagesGetResponse getRefundMessages(Map<String,String> params,Long refundId,String refundPhase) throws ApiException{
		TaobaoClient client = new DefaultTaobaoClient(params.get("proxUrl"), params.get("appKey"), params.get("secret"));
		RefundMessagesGetRequest req = new RefundMessagesGetRequest();
		req.setFields("id,refund_id,owner_id,owner_nick,content,pic_urls,created,message_type,refund_phase,owner_role");
		req.setRefundId(refundId);
		req.setRefundPhase(refundPhase);
		RefundMessagesGetResponse response = client.execute(req , params.get("appSession"));
		return response;
	}
}
